import prisma from "~~/lib/prisma";
import { userCreateSchema } from "~~/shared/schemas/user.schema"; // Import shared schema

export default defineEventHandler(async (event) => {
  const body = await readBody(event);

  // Validate the request body using the shared Zod schema
  const parsed = userCreateSchema.safeParse(body);

  if (!parsed.success) {
    // If validation fails, throw an H3Error with details
    throw createError({
      statusCode: 400,
      statusMessage: "Validation Failed",
      data: parsed.error.flatten(), // Provide detailed validation errors
    });
  }

  // Use the validated data (parsed.data) for creating the user
  try {
    return await prisma.user.create({
      data: parsed.data, // Use validated data
    });
  } catch (error: any) {
    // Handle potential Prisma errors (e.g., unique constraint violation)
    // You might want more specific error handling here
    throw createError({
      statusCode: 500,
      statusMessage: "Could not create user",
      data: error.message,
    });
  }
});
